package com.cocos.game;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtils {

    public static byte[] fileToByte(File file) {
        if (file == null || !file.exists()) {
            return new byte[0];
        }
        byte[] buffer = new byte[0];
        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;
        try {
            fis = new FileInputStream(file);
            bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n = fis.read(b);
            while (n != -1) {
                bos.write(b, 0, n);
                n = fis.read(b);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (bos != null) bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return buffer;
    }

    public static void saveByteByFile(byte[] data, File file) {
        if (file == null || data == null) {
            return;
        }
        FileOutputStream fileOutputStream = null;
        try {
            if (!file.exists()) {
                boolean mkdirs = file.getParentFile().mkdirs();
                boolean created = file.createNewFile();
            }
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null) fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

